package cn.edu.niit.server.service.impl;

import cn.edu.niit.server.service.AiFaceService;
import cn.edu.niit.server.service.dto.FaceItem;
import com.baidu.aip.face.AipFace;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AiFaceServiceImpl implements AiFaceService {

    @Value("${baidu.ai.appid}")
    String APP_ID;

    @Value("${baidu.ai.apikey}")
    String API_KEY;

    @Value("${baidu.ai.secret}")
    String SECRET_KEY;

    /**
     * 初始化百度ai调用端
     * @return
     */
    public AipFace getClient() {
        return new AipFace(APP_ID, API_KEY, SECRET_KEY);
    }

    @Override
    public List<FaceItem> detectImageBase64(String image_base64, String maxum) {
        //1、构造人脸检测需要的参数：需要获取的人脸字段信息、最大检测数量、照片类型
        HashMap<String, String> options = new HashMap<>();
        options.put("face_field", "age,beauty,expression,face_shape,gender,glasses");
        options.put("max_face_num", maxum);
        options.put("face_type", "LIVE");

        String image = image_base64;
        String image_type = "BASE64";
        //2、向百度ai发起请求
        AipFace client = getClient();
        JSONObject res = client.detect(image, image_type, options);
        //成功调用
        if (res.has("error_code") && res.getLong("error_code") == 0L) {
            JSONObject resResult = res.getJSONObject("result");
            //检测到有人脸信息
            if (resResult.has("face_num") && resResult.getInt("face_num") > 0) {
                List<FaceItem> result = new ArrayList<FaceItem>();
                JSONArray faceArray = resResult.getJSONArray("face_list");
                for (int i = 0; i < faceArray.length(); i++) {
                    FaceItem faceItem = new FaceItem();
                    JSONObject faceJson = faceArray.getJSONObject(i);

                    faceItem.setFaceToken(faceJson.getString("face_token"));
                    faceItem.setAge(faceJson.getDouble("age"));
                    faceItem.setBeauty(faceJson.getInt("beauty"));

                    JSONObject expression = faceJson.getJSONObject("expression");
                    faceItem.setExpression(expression.getString("type"));

                    JSONObject gender = faceJson.getJSONObject("gender");
                    faceItem.setGender(gender.getString("type"));

                    JSONObject glasses = faceJson.getJSONObject("glasses");
                    faceItem.setGlasses(glasses.getString("type"));

                    JSONObject faceShape = faceJson.getJSONObject("face_shape");
                    faceItem.setFaceShape(faceShape.getString("type"));
                    result.add(faceItem);
                }
                return result;
            }
        }
        return null;
    }
}
